﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;

namespace HQLAddin.Highlighting.Classificators.BaseClass
{
	internal abstract class RegexBasedClassifier : IClassifier
	{
		private readonly IClassificationTypeRegistryService classificationRegistry;

		protected RegexBasedClassifier(IClassificationTypeRegistryService classificationRegistry)
		{
			this.classificationRegistry = classificationRegistry;
		}

		public abstract string FormatterName { get; }

		public abstract IEnumerable<Regex> Regexs { get; }


		public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
		{
			if (!span.IsInQueryTag()) return Enumerable.Empty<ClassificationSpan>().ToList();
			var startline = span.Start.GetContainingLine();
			var endline = (span.End - 1).GetContainingLine();
			var text = span.Snapshot.GetText(new SnapshotSpan(startline.Start, endline.End));

			return (from regex in Regexs
				   from match in regex.Matches(text).OfType<Match>()
				   select new ClassificationSpan(new SnapshotSpan(span.Snapshot, span.Start.Position + match.Index, match.Length), classificationRegistry.GetClassificationType(FormatterName)))
				   .ToList();
		}

		public event EventHandler<ClassificationChangedEventArgs> ClassificationChanged;
	}
}